package com.fafa.pos.dao.impl;

import android.content.ContentValues;
import android.database.Cursor;
import com.fafa.pos.dao.DBUtil;
import com.fafa.pos.dao.IPOSInfoDao;
import com.fafa.pos.pojo.CardInfo;
import com.fafa.pos.pojo.POSInfo;
import com.fafa.pos.util.DateUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by ZhouBing on 2017/8/10.
 *
 * SQLite -- T_POSINfO
 */
public class POSInfoDaoImpl implements IPOSInfoDao{

    private DBUtil dbUtil;
    private ConfigDaoImpl configDao;

    public POSInfoDaoImpl(DBUtil dbUtil) {
        this.dbUtil = dbUtil;
        configDao = new ConfigDaoImpl(dbUtil);
    }
    @Override
    public void savePOSInfoList(List<POSInfo> posInfos) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        dbUtil.getDB().beginTransaction();
        String updateDate = "1900-00-00 00:00:00.000";
        try{
            for (POSInfo posInfo:posInfos) {

                //Id存在则更新不存在新增
                String sql = "select POS_ID from T_POSINfO where POS_ID = ?";
                Cursor cursor = dbUtil.getDB().rawQuery(sql,new String[]{posInfo.getPOSId()});

                ContentValues contentValues = new ContentValues();
                contentValues.put("POS_ID",posInfo.getPOSId());
                contentValues.put("POS_CODE",posInfo.getPOSCode());
                contentValues.put("POS_NAME",posInfo.getPOSName());
                contentValues.put("IS_TERMINAL",posInfo.getIsTeraminal());
                contentValues.put("STATUS",posInfo.getStatus());
                contentValues.put("UPDATE_DATE",posInfo.getUpdate());

                Date tempDate = sdf.parse(posInfo.getUpdate());

                if (sdf.parse(updateDate).before(tempDate)) {
                    updateDate=sdf.format(tempDate);
                }

                if(cursor.moveToNext()){
                    dbUtil.getDB().update("T_POSINfO",contentValues," POS_ID = ?",new String[]{posInfo.getPOSId()});
                }else{
                    dbUtil.getDB().insert("T_POSINfO",null,contentValues);
                }
                if(cursor!=null){
                    cursor.close();
                }
            }
            configDao.saveItem("T_POSINfO_UPDATE_DATE", updateDate);
            dbUtil.getDB().setTransactionSuccessful();
        } catch (ParseException e) {
            e.printStackTrace();
        } finally {
            dbUtil.getDB().endTransaction();
            dbUtil.close();
        }
    }
}
